package com.sky.service.impl;

import com.sky.entity.WalletTransactions;
import com.sky.entity.Wallets;
import com.sky.mapper.WalletsMapper;
import com.sky.service.WalletTransactionsService;
import com.sky.service.WalletsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.WalletsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GHOSTER by RemSynch
 * @since 2024-10-24
 */
@Service
public class WalletsServiceImpl extends ServiceImpl<WalletsMapper, Wallets> implements WalletsService {

    @Autowired
    private WalletTransactionsService walletTransactionsService;

    @Autowired
    private WalletsMapper walletsMapper;

    @Transactional
    public void createWalletAndRecordTransaction(Long userId, BigDecimal amount, Long accountAId) {
        // 创建新的钱包
        Wallets newWallet = new Wallets();
        newWallet.setUserId(userId);
        newWallet.setAccountAId(accountAId);
        newWallet.setBalance(amount);
        newWallet.setFrozenAmount(BigDecimal.ZERO);
        newWallet.setStatus(0); // 假设 1 表示激活状态

        // 保存新钱包
        walletsMapper.insert(newWallet);

        // 记录交易
        WalletTransactions transaction = new WalletTransactions();
        transaction.setWalletId(newWallet.getId());
        transaction.setAmount(amount);
        transaction.setTransactionType(0); // 交易类型为存款（后台操作）
        transaction.setDescription("Initial deposit to create wallet");

        // 保存交易记录
        walletTransactionsService.save(transaction);
    }

    @Override
    public List<WalletsVO> getWalletsByUser() {
        return walletsMapper.getWallets();
    }
}